package com.moon.admin.tools.servcie;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.moon.admin.framework.util.ToolUtils;
import com.moon.admin.tools.entity.GenTableColumn;
import com.moon.admin.tools.mapper.GenTableColumnMapper;
import com.moon.admin.tools.utils.GenUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 业务字段 服务层实现
 *
 * @author ninglong
 */
@Service
public class GenTableColumnService extends ServiceImpl<GenTableColumnMapper, GenTableColumn> {


    /**
     * 查询业务字段列表
     * @param tableId 业务字段编号
     * @return 业务字段集合
     */
    public List<GenTableColumn> selectColumnListByTableIdAndTableName(Integer tableId,String tableName) {
        List<GenTableColumn> dbColumnList = this.baseMapper.selectDbTableColumnsByName(tableName);
        if(tableId==null){
            dbColumnList.forEach(entity-> GenUtils.initColumnField(entity));
            return dbColumnList;
        }
        List<GenTableColumn> genColumnList =  this.baseMapper.selectList(Wrappers.<GenTableColumn>lambdaQuery().eq(GenTableColumn::getTableId,tableId));
        if(ToolUtils.isEmpty(genColumnList)){
            return dbColumnList;
        }
        List<GenTableColumn> columns = Lists.newArrayList();
        Map<String,GenTableColumn> genTableColumnMap = genColumnList.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));
        for(GenTableColumn entity:dbColumnList){
            GenTableColumn genTableColumn = genTableColumnMap.get(entity.getColumnName());
            if(genTableColumn==null){
                columns.add(entity);
            }else{
                GenTableColumn column = ToolUtils.copy(genTableColumn,GenTableColumn.class);
                column.setColumnType(entity.getColumnType());
                column.setIsRequired(entity.getIsRequired());
                column.setIsPk(entity.getIsPk());
                columns.add(column);
            }
        }
        return columns;
    }
}
